import 'dart:collection';

import 'package:flutter/services.dart';

///消息管理通道-BasicMessageChannel
///用于传递字符串和半结构化的信息，双向通道，原生可以多次向flutter发送信息
///适用于碎片化连续性的消息传递
class MessageChannelUtils {
  static const MESSAGE_CHANNEL_NAME = "cn.xqw/message";

  ///1、方法通道名称
  static late BasicMessageChannel _messageChannel;

  static initChannels() {
    _messageChannel =
        BasicMessageChannel(MESSAGE_CHANNEL_NAME, StandardMessageCodec());
  }

  static Future<MessageResponse> getResult(MessageRequest req) async {
    return _messageChannel
        .send(req.toJson())
        .then((value) => MessageResponse.fromValue(value));
  }
}

class MessageRequest {
  final String name;
  final int age;

  MessageRequest(this.name, this.age);

  HashMap<String, dynamic> toJson() {
    return HashMap<String, dynamic>()
      ..['name'] = name
      ..['age'] = age;
  }
}

class MessageResponse {
  final String message;
  final int code;

  MessageResponse(this.message, this.code);

  factory MessageResponse.fromValue(dynamic response) {
    return MessageResponse(response['msg'], response['code']);
  }
}

class Message1 {
  MessageRequest get req => MessageRequest("", 0);
}

class Message2 extends Message1 {
  Message1? msg;

  MessageRequest get req => msg?.req ?? MessageRequest("", 0);
}
